//
//  YZMPatchManager.m
//  YZMicroStock
//
//  Created by sum1818 on 16/9/22.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMPatchManager.h"
#import "YZClient.h"

@interface YZMPatchManager()
+ (NSDictionary*) PATCHES;
@end
static NSDictionary *patches = nil;
static double lastSyncTime = 0;
@implementation YZMPatchManager

+ (NSDictionary*) PATCHES
{
    if (patches == nil) {
        NSDictionary *infoDictionary =[[NSBundle mainBundle] infoDictionary];
        NSString *patchName = [@"ver_" stringByAppendingFormat:@"%@.patch", [infoDictionary objectForKey:@"CFBundleVersion"]];
        patches = @{patchName: @100000};
    }
    return patches;
}

+ (NSString*) getPatchFileByName:(NSString *)filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *patchDir = [docDir stringByAppendingPathComponent:@"Patches"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:patchDir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:patchDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [patchDir stringByAppendingPathComponent:filename];
}

+ (NSString*) getPatchContentByName:(NSString *)filename
{
    NSString *filepath = [YZMPatchManager getPatchFileByName:filename];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        return [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
    } else {
        return nil;
    }
}

+ (void) syncFromServer:(NSString *)filename success:(void (^)(NSString *filepath))success
{
    double currTime = [[NSDate date] timeIntervalSince1970];
    if (currTime - lastSyncTime > 30) {//超过30秒就更新
        lastSyncTime = currTime;
        [YZClient downloadPatch:filename success:^(NSURLSessionDownloadTask *task, id responseObject) {
            //下载文件成功,刷新补丁
            NSLog(@"patch filepath:%@", responseObject);
            if (success) {
                success(responseObject);
            }
        } failure:^(NSError *error) {
            NSLog(@"sync patch error");
        }];
    }
}

+ (BOOL) patchIsUseful:(NSString *)filename
{
    NSString *filepath = [YZMPatchManager getPatchFileByName:filename];
    NSString *datepath = [filepath stringByAppendingString:@".date"];
    NSString *date = [NSString stringWithContentsOfFile:datepath encoding:NSUTF8StringEncoding error:nil];
    double doubleDate = 0;
    if (date.length > 0) {
        date = [date componentsSeparatedByString:@"||"][1];
        doubleDate = [date doubleValue];
    }
    NSNumber *number = [YZMPatchManager PATCHES][filename];
    double localDate = [number doubleValue];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath] && doubleDate > localDate && localDate > 1) {//本地文件存在则使用
        return YES;
    }
    return NO;
}

@end
